const { app, BrowserWindow, ipcMain } = require('electron');
const { Tray, Menu,nativeImage,session  } = require('electron');
const { encode, decode } = require('@/utils/MessageProtocol');
const path = require('node:path');
const net = require('net');
// 全局 socket 连接和缓冲区
let globalSocket = null;
let globalBuffer = Buffer.alloc(0);
let pendingCallbacks = new Map(); // 用于存储 socket-connect 的回调
let tray = null;
let loginWindow = null;
let mainWindow = null;
let registerWindow = null;
let videoChatWindow = null;
let globalToken = '';
let username = '';

function createLoginWindow() {
  loginWindow = new BrowserWindow({
    width: 500,
    height: 700,
    frame: false, // 关键：关闭默认标题栏
    icon: path.resolve(app.getAppPath(), './src/assets/icons/app.ico'),
    webPreferences: {
      preload: LOGIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      contextIsolation: true,
      webSecurity: false,//后端设好跨域请求后这行去掉
    },
  });
  loginWindow.setMenuBarVisibility(false);
  loginWindow.loadURL(LOGIN_WINDOW_WEBPACK_ENTRY);
}

const createRegisterWindow = ()=>{
  registerWindow = new BrowserWindow({
    width:400,height:550,
    frame:false,
    webPreferences:{
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      contextIsolation: true,
      webSecurity: false,
    }
  });
  registerWindow.setMenuBarVisibility(false);
  registerWindow.loadURL(REGISTER_WINDOW_WEBPACK_ENTRY); // 新的注册页面入口
  registerWindow.on('closed', () => (registerWindow = null));
}

function createChatWindow(userId) {
  const chatWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      contextIsolation: true,
      webSecurity: false,
      additionalArguments: [`--user-id=${userId}`] // 关键传参
    },
  });

  chatWindow.setMenuBarVisibility(false);
  chatWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
}



function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    frame: false, // 关键：关闭默认标题栏
    icon: path.resolve(app.getAppPath(), './src/assets/icons/tray.ico'),
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      contextIsolation: true,
      webSecurity: false,
    },
  });
  console.log("path：",path.resolve(app.getAppPath(), './src/assets/icons/tray.ico'));
  mainWindow.setMenuBarVisibility(false);
  mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
}

const createvideoChatWindow = ()=>{
  videoChatWindow = new BrowserWindow({
    width:400,height:550,
    frame:false,
    webPreferences:{
      preload: VIDEO_WINDOW_PRELOAD_WEBPACK_ENTRY,
      contextIsolation: true,
      webSecurity: false,
    }
  });
  videoChatWindow.setMenuBarVisibility(false);
  videoChatWindow.loadURL(VIDEO_WINDOW_WEBPACK_ENTRY); 
  videoChatWindow.on('closed', () => (videoChatWindow = null));
}

function createTray() {
  const iconPath = path.resolve(app.getAppPath(), 'src/assets/icons/tray-1.png'); 
  let trayIcon = nativeImage.createFromPath(iconPath);

    if (!trayIcon.isEmpty()) {
        // 根据系统 DPI 调整图标大小
        const scaleFactor = process.platform === 'darwin' ? 2 : 1;
        trayIcon = trayIcon.resize({ width: 16 * scaleFactor, height: 16 * scaleFactor });

        tray = new Tray(trayIcon);

        tray.setToolTip('SIX');
        tray.setContextMenu(Menu.buildFromTemplate([
            { label: '显示主窗口', click: () => { mainWindow?.show(); } },
            { label: '退出', click: () => { app.quit(); } }
        ]));
    }
    /*这样也行 
    const fs = require('fs');
    const iconBase64 = fs.readFileSync(iconPath).toString('base64');
    const trayIcon = nativeImage.createFromDataURL(`data:image/png;base64,${iconBase64}`);

    console.log("tray: ",trayIcon.isEmpty());
    tray = new Tray(trayIcon);

    tray.setToolTip('SIX');
    tray.setContextMenu(Menu.buildFromTemplate([
      { label: '显示主窗口', click: () => { mainWindow?.show(); } },
      { label: '退出', click: () => { app.quit(); } }
    ])); */
}

app.whenReady().then(() => {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    const responseHeaders = details.responseHeaders;
  
    const policy = [
      "default-src 'self';",
      "connect-src 'self'http://172.20.10.3:8089 ws://172.20.10.3:3000 http://172.20.10.3:8089 ws://172.20.10.3:3000;",
      "script-src 'self' 'unsafe-eval' 'unsafe-inline';",
      "style-src 'self' 'unsafe-inline';",
      "img-src 'self' data: https://fastly.picsum.photos https://picsum.photos; "
    ].join(' ');
  
    responseHeaders['Content-Security-Policy'] = [policy];
    responseHeaders['content-security-policy'] = [policy];
  
    callback({ cancel: false, responseHeaders });
  });
  
  createLoginWindow();
  createvideoChatWindow();
  createTray();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
//打开注册窗口
ipcMain.on('open-register-window', () => {
  if (registerWindow) {
    registerWindow.focus();
    return;
  }
  createRegisterWindow();
});

ipcMain.on('login-success', (event, data) => {
  console.log("login-success");
  // if (loginWindow) loginWindow.close();
  createMainWindow();

});

ipcMain.handle('socket-connect', (event, host, port,user) => {
  return new Promise((resolve, reject) => {
    username = user;
    // 如果已经有连接，直接返回
    if (globalSocket && globalSocket.readyState === 'open') {
      resolve('already connected');
      return;
    }

    // 检查用户名是否已设置
    if (!username) {
      reject('Username not set yet');
      return;
    }

    globalSocket = new net.Socket();
    
    // 存储回调函数，以便在多个窗口中使用
    pendingCallbacks.set('connect', { resolve, reject });
    pendingCallbacks.set('error', reject);

    globalSocket.connect(port, host, () => {
      globalBuffer = Buffer.alloc(0);
      
      // 发送登录包
      const loginBuffer = encode(0x05, Buffer.from(username, 'utf-8'));
      globalSocket.write(loginBuffer);
      console.log("loginBuffer:", loginBuffer);
      
      // 触发所有等待的连接回调
      if (pendingCallbacks.has('connect')) {
        pendingCallbacks.get('connect').resolve('connected');
        pendingCallbacks.delete('connect');
      }
    });

    globalSocket.on('data', (data) => {
      console.log("有没有收到消息,",data);
      globalBuffer = Buffer.concat([globalBuffer, data]);
      console.log("buffer:", globalBuffer);
      
      let decodedMessage;
      while ((decodedMessage = decode(globalBuffer)) !== null) {
        console.log("decodedMessage", decodedMessage);
        const { type, content } = decodedMessage;
        
        // 向所有窗口广播消息
        BrowserWindow.getAllWindows().forEach(window => {
          window.webContents.send('socket-message', {
            type,
            content: JSON.parse(content.toString())
          });
        });
        
        globalBuffer = globalBuffer.slice(5 + content.length);
      }
    });

    globalSocket.on('error', (err) => {
      console.error("Socket error:", err);
      
      // 触发所有错误回调
      if (pendingCallbacks.has('error')) {
        pendingCallbacks.get('error')(err.message);
        pendingCallbacks.delete('error');
      }
      
      disconnectSocket();
    });

    globalSocket.on('close', () => {
      console.log("Socket connection closed");
      disconnectSocket();
    });
  });
});

function disconnectSocket() {
  if (globalSocket) {
    globalSocket.destroy();
    globalSocket = null;
    globalBuffer = Buffer.alloc(0);
  }
}

ipcMain.on('socket-send', (event, { type, content }) => {
  
  if (!globalSocket || globalSocket.readyState !== 'open') {
    console.log("Socket is not connected");
    return;
  }
  
  // 检查 content 是否有效
  if (!content) {
    console.log("Invalid content to send:", content);
    return;
  }
  
  try {
    const contentBuffer = Buffer.from(content, 'utf-8');
    const encodedBuffer = encode(type, contentBuffer);
    console.log("encodedBuffer:", encodedBuffer);
    globalSocket.write(encodedBuffer);
  } catch (error) {
    console.error("Error sending message:", error);
  }
});



// //socket 先注释掉，测试多用户聊天用，之后再取消
// ipcMain.handle('socket-connect', (event, host, port) => {
//   return new Promise((resolve, reject) => {
//     socket = new net.Socket();

//     socket.connect(port, host, () => {
//       resolve('connected');
//     });

//     socket.on('data', (data) => {
//       event.sender.send('socket-message', data.toString());
//     });

//     socket.on('error', (err) => {
//       reject(err.message);
//     });
//   });
// });

// ipcMain.on('socket-send', (event, data) => {
//   if (socket) {
//     socket.write(data);//可能需要封装成json
//   }
// });

ipcMain.on('save-token', (event, token) => {
  globalToken = token;
});

ipcMain.handle('get-token', () => {
  return globalToken;
});

ipcMain.handle('get-username',()=>{
  return username;
})

//自定义顶部栏响应
ipcMain.on('minimize-window', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  win?.minimize();
});
ipcMain.on('close-window', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  win?.close();
});
ipcMain.on('toggle-maximize', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win?.isMaximized()) {
    win.unmaximize();
  } else {
    win?.maximize();
  }
});

